[org 0x7c00]

; 清屏
mov ax, 3
int 0x10

; 初始化寄存器
mov ax, 0
mov ds, ax
mov es, ax
mov sp, 0x7c00

mov si, boot_msg
call print

; 读取 loader
mov edi, 0x1000
mov ecx, 2
mov bl, 4
call read_disk

; 跳转到 loader
jmp 0:0x1000

print:
    mov ah, 0x0e
.next:
    mov al ,[si]
    cmp al, 0
    jz .done
    int 0x10
    inc si
    jmp .next
.done:
    ret

read_disk:
    mov dx, 0x1f2 ; 传入读取扇区数量
    mov al, bl
    out dx, al

    ; 传入 LBA 编号
    inc dx
    mov al, cl
    out dx, al

    inc dx
    shr ecx, 8
    mov al, cl
    out dx, al

    inc dx
    shr ecx, 8
    mov al, cl
    out dx, al

    inc dx
    shr ecx, 8
    mov al, cl
    and al, 0b0000_1111

    ; 设置模式
    or al, 0b1110_0000
    out dx, al

    ; 输入读硬盘命令
    inc dx
    mov al, 0x20
    out dx, al

    xor ecx, ecx
    mov cl, bl
.read:
    call .wait
    call .reads
    loop .read

    ret

; 等待硬盘
.wait:
    mov dx, 0x1f7
.next:
    jmp $ + 2
    jmp $ + 2
    jmp $ + 2
    in al, dx
    and al, 0b1000_1000
    cmp al, 0b0000_1000
    jnz .next

    ret

.reads:
    mov dx, 0x1f0
    push cx
    mov cx, 256
.loop:
    in ax, dx
    mov word [edi], ax
    add edi, 2
    loop .loop

    pop cx
    ret

boot_msg:
    db "Booting LucnxOS...",10,13,0

times 510-($-$$) db 0

; MBR 认证
dw 0xaa55